const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const FoodItemSchema = new Schema({
  foodId: { type: Schema.Types.ObjectId, ref: 'Food' },
  name: { type: String, required: true },
  quantity: { type: Number, required: true },
  unit: { type: String, required: true },
  calories: { type: Number, required: true },
  carbs: { type: Number, default: 0 },
  protein: { type: Number, default: 0 },
  fat: { type: Number, default: 0 },
  fiber: { type: Number, default: 0 },
  sugar: { type: Number, default: 0 },
  imageUrl: { type: String },
  // 自定义食物的额外字段
  isCustom: { type: Boolean, default: false },
  category: { type: String },
  baseAmount: { type: Number },
  baseUnit: { type: String }
});

const DietMealSchema = new Schema({
  userId: { type: Schema.Types.ObjectId, ref: 'User', required: true },
  date: { type: Date, required: true },
  mealType: { 
    type: String, 
    required: true,
    enum: ['早餐', '午餐', '晚餐', '加餐']
  },
  time: { type: String, required: true }, // 餐食时间，格式如"08:30"
  foods: [FoodItemSchema],
  totalCalories: { type: Number, default: 0 },
  totalCarbs: { type: Number, default: 0 },
  totalProtein: { type: Number, default: 0 },
  totalFat: { type: Number, default: 0 },
  totalFiber: { type: Number, default: 0 },
  totalSugar: { type: Number, default: 0 },
  note: { type: String },
  tags: [String],
  createdAt: { type: Date, default: Date.now },
  updatedAt: { type: Date, default: Date.now }
});

// 自动计算总值
DietMealSchema.pre('save', function(next) {
  if (this.foods && this.foods.length > 0) {
    this.totalCalories = this.foods.reduce((sum, food) => sum + food.calories, 0);
    this.totalCarbs = this.foods.reduce((sum, food) => sum + food.carbs, 0);
    this.totalProtein = this.foods.reduce((sum, food) => sum + food.protein, 0);
    this.totalFat = this.foods.reduce((sum, food) => sum + food.fat, 0);
    this.totalFiber = this.foods.reduce((sum, food) => sum + food.fiber, 0);
    this.totalSugar = this.foods.reduce((sum, food) => sum + food.sugar, 0);
  }
  this.updatedAt = Date.now();
  next();
});

// 创建复合索引，用于快速查询用户特定日期的餐食
DietMealSchema.index({ userId: 1, date: 1 });

module.exports = mongoose.model('DietMeal', DietMealSchema); 